package com.xtgg.history;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.loopj.android.http.RequestParams;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.media.QQShareContent;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.sso.SinaSsoHandler;
import com.umeng.socialize.sso.UMQQSsoHandler;
import com.umeng.socialize.sso.UMSsoHandler;
import com.umeng.socialize.weixin.controller.UMWXHandler;
import com.umeng.socialize.weixin.media.CircleShareContent;
import com.umeng.socialize.weixin.media.WeiXinShareContent;
import com.xtgg.R;
import com.xtgg.login.LoginActivity;
import com.xtgg.manager.BaseActivity;
import com.xtgg.model.Resp;
import com.xtgg.sys.Constants;
import com.xtgg.sys.DemoApp;
import com.xtgg.util.MgqDataHandler;
import com.xtgg.util.MgqRestClient;
import com.xtgg.util.PreferencesUtils;
import com.xtgg.util.TLog;
import com.xtgg.util.ToastUtil;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.View.MeasureSpec;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class HistorySumActivity extends BaseActivity implements OnClickListener {
	MyAdapter mAdapter;
	JSONArray mArray = null;
	ArrayList<Integer> mStart = new ArrayList<Integer>();
	int mSelected = 0;
	
	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_history_sum);

		((TextView) findViewById(R.id.center)).setText("足迹");
		MobclickAgent.onEvent(this, ((TextView) findViewById(R.id.center))
				.getText().toString());

		((Button) findViewById(R.id.left)).setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
		((Button) findViewById(R.id.right)).setText("分享");
		((Button) findViewById(R.id.right)).setTextColor(Color
				.parseColor("#EE7C1C"));
		((Button) findViewById(R.id.left)).setTextColor(Color
				.parseColor("#EE7C1C"));
		findViewById(R.id.left).setOnClickListener(this);
		findViewById(R.id.right).setOnClickListener(this);

		final Date date = new Date(System.currentTimeMillis());
		((Button)findViewById(R.id.year)).setText(String.valueOf(1900 + date.getYear()));
		
		findViewById(R.id.year).setOnClickListener(this);
		findViewById(R.id.month0).setOnClickListener(this);
		findViewById(R.id.month1).setOnClickListener(this);
		findViewById(R.id.month2).setOnClickListener(this);
		findViewById(R.id.month3).setOnClickListener(this);
		findViewById(R.id.month4).setOnClickListener(this);
		findViewById(R.id.month5).setOnClickListener(this);
		findViewById(R.id.month6).setOnClickListener(this);
		findViewById(R.id.month7).setOnClickListener(this);
		findViewById(R.id.month8).setOnClickListener(this);
		findViewById(R.id.month9).setOnClickListener(this);
		findViewById(R.id.month10).setOnClickListener(this);
		findViewById(R.id.month11).setOnClickListener(this);

		findViewById(R.id.btn0).setOnClickListener(this);
		findViewById(R.id.btn1).setOnClickListener(this);
		findViewById(R.id.btn2).setOnClickListener(this);
		findViewById(R.id.confirm).setOnClickListener(this);
		
		((Button)findViewById(R.id.month0 + date.getMonth())).setSelected(true);
		
		final PullToRefreshListView ptrlvHeadlineNews = (PullToRefreshListView) findViewById(R.id.listview);
		ptrlvHeadlineNews
				.setMode(com.handmark.pulltorefresh.library.PullToRefreshBase.Mode.DISABLED);
		ptrlvHeadlineNews
				.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
					@Override
					public void onRefresh(
							PullToRefreshBase<ListView> refreshView) {
						sendHttpRequest();
					}
				});

		ListView listview = ptrlvHeadlineNews.getRefreshableView();
		mAdapter = new MyAdapter();
		listview.setAdapter(mAdapter);
		listview.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				
				findViewById(R.id.layout1).setVisibility(View.GONE);
				JSONObject item = mArray.getJSONObject(arg2 - 1);
				
				Intent intent = new Intent(HistorySumActivity.this,MapLocationActivity.class);
				intent.putExtra("addr", item.getString("place"));
				intent.putExtra("lat", item.getDoubleValue("latitude"));
				intent.putExtra("lng", item.getDoubleValue("longitude"));
				startActivity(intent);
			
			}
		});

		sendHttpRequest();
		
		final Handler handler = new Handler(){
			public void handleMessage(Message msg)
			{
				int xPos = (int) findViewById(R.id.month0 + date.getMonth()).getX();
				HorizontalScrollView hs = (HorizontalScrollView)findViewById(R.id.hs);
				hs.smoothScrollTo(xPos, 0);
				
				super.handleMessage(msg);
			}
		};
		
		new Timer().schedule(new TimerTask(){
			@Override
			public void run() {
				handler.sendEmptyMessage(0);
			}
		}, 200);
	}
	
	boolean hasDraw;
	Dialog mDialog = null;
	void showQuery() {
		mDialog = new Dialog(this, R.style.Dialog_Fullscreen);
		mDialog.setContentView(R.layout.dialog_share);
		mDialog.findViewById(R.id.action0).setOnClickListener(this);
		mDialog.findViewById(R.id.action1).setOnClickListener(this);
		mDialog.findViewById(R.id.action2).setOnClickListener(this);
		mDialog.findViewById(R.id.action3).setOnClickListener(this);
		mDialog.findViewById(R.id.login).setOnClickListener(this);
		mDialog.show();
	}
	
	 public Bitmap convertViewToBitmap(View view) {
		 WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
		 int width = wm.getDefaultDisplay().getWidth();
		 int height = wm.getDefaultDisplay().getHeight();
		 
		 Bitmap b = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);  
		 view.draw(new Canvas(b));
		 return b;
	 }
	
	 static public Bitmap mScreenShot = null;
	@Override
	public void onClick(View arg0) {
		findViewById(R.id.layout1).setVisibility(View.GONE);
		
		switch (arg0.getId()) {
		case R.id.right:
			showQuery();
			break;
			
		case R.id.login:
			mDialog.dismiss();
			break;
			
		case R.id.action0:
		{
			mScreenShot = convertViewToBitmap(findViewById(R.id.screen));
			
			Intent intent = new Intent(this,ShareActivity.class);
			intent.putExtra("type", 0);
			intent.putExtra("content", "小兔乖乖足迹");
			startActivity(intent);
		}
			mDialog.dismiss();
			break;

		case R.id.action1:
		{
			mScreenShot = convertViewToBitmap(findViewById(R.id.screen));
			
			Intent intent = new Intent(this,ShareActivity.class);
			intent.putExtra("type", 1);
			intent.putExtra("content", "小兔乖乖足迹");
			startActivity(intent);
		}
			mDialog.dismiss();
			break;

		case R.id.action2:
		{
			mScreenShot = convertViewToBitmap(findViewById(R.id.screen));
			
			Intent intent = new Intent(this,ShareActivity.class);
			intent.putExtra("type", 2);
			intent.putExtra("content", "小兔乖乖足迹");
			startActivity(intent);
		}
			mDialog.dismiss();
			break;

		case R.id.action3:
		{
			mScreenShot = convertViewToBitmap(findViewById(R.id.screen));
			
			Intent intent = new Intent(this,ShareActivity.class);
			intent.putExtra("type", 3);
			intent.putExtra("content", "小兔乖乖足迹");
			startActivity(intent);
		}
			mDialog.dismiss();
			break;
			
		case R.id.btn2:
			startActivity(new Intent(this,SortActivity.class));
			break;

		case R.id.btn1:
			startActivity(new Intent(this,HistoryMapActivity.class));
			break;
			
		case R.id.year:
			showSex();
			break;
			
		case R.id.month0:
		case R.id.month1:
		case R.id.month2:
		case R.id.month3:
		case R.id.month4:
		case R.id.month5:
		case R.id.month6:
		case R.id.month7:
		case R.id.month8:
		case R.id.month9:
		case R.id.month10:
		case R.id.month11:
			Button button = (Button)arg0;
			if(button.isSelected()) button.setSelected(false);
			else button.setSelected(true);
			sendHttpRequest();
			break;
		
		case R.id.confirm:
			sendModifyHttpRequest();
			break;
		}
	}
	
	private void sendModifyHttpRequest() {
		String content = ((EditText)findViewById(R.id.content)).getText().toString();
		if(content.length() == 0) 
		{
			ToastUtil.showToastWithAlertPic("请输入修改内容");
			return;
		}
		
		MgqDataHandler loginHandler = new MgqDataHandler(this, true, false) {
			@Override
			public void onSuccess(String response) {
				TLog.d(TAG, "response=" + response);
				Resp ruser = JSON.parseObject(response, Resp.class);
				if (ruser.getState().equals("1")) {
					ToastUtil.showToastWithAlertPic("足迹修改成功");
					sendHttpRequest();

					findViewById(R.id.layout0).setVisibility(View.GONE);
					findViewById(R.id.layout1).setVisibility(View.GONE);
				}
				else if (ruser.getState().equals("2"))
				{
					showExitDialog();
				} 
				else {
					ToastUtil.showToastWithAlertPic(ruser.getMessage());
				}
			}
		};

		JSONObject item = mArray.getJSONObject(mSelected);
		
		RequestParams params = new RequestParams();
		params.put("act", "updateFootMark");
		params.put("userid", PreferencesUtils.getString(this, "userid"));
		params.put("province", item.getString("province"));
		params.put("city", item.getString("city"));
		params.put("place", item.getString("place"));
		params.put("alias", content);
		MgqRestClient.get(Constants.INFOMGT, params, loginHandler);
	}
	
	@SuppressWarnings("deprecation")
	public void showSex() {
		Date date = new Date(System.currentTimeMillis());
		int year = 1900 + date.getYear();
		
		final String[] items = new String[20];
		for(int i = year; i > year - 20; i--)
		{
			items[year - i] = String.valueOf(i);
		}
		
		new AlertDialog.Builder(this).setTitle("选择年份")
		.setItems(items, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				((Button)findViewById(R.id.year)).setText(items[which]);
				sendHttpRequest();
			}
		}).show();
	}
	
	private void sendHttpRequest() {
		mStart.removeAll(mStart);
		mArray = null;
		mAdapter.notifyDataSetChanged();
		
		MgqDataHandler loginHandler = new MgqDataHandler(this, true, false) {
			@Override
			public void onSuccess(String response) {
				TLog.d(TAG, "response=" + response);
				Resp ruser = JSON.parseObject(response, Resp.class);
				if (ruser.getState().equals("1")) {
					mArray = JSON.parseObject(response).getJSONArray("data");
					
					int count = mArray.size();
					String city = "";
					for(int i = 0; i < count; i++)
					{
						JSONObject item = mArray.getJSONObject(i);
						if(!item.getString("city").equals(city))
						{
							city = item.getString("city");
							mStart.add(Integer.valueOf(i));
						}
					}
					
					mStart.add(Integer.valueOf(count));
				}
				else if (ruser.getState().equals("2"))
				{
					showExitDialog();
				} 
				else {
					ToastUtil.showToastWithAlertPic(ruser.getMessage());
				}
				
				mAdapter.notifyDataSetChanged();
			}
		};
		
		StringBuffer buffer = new StringBuffer();
		for(int i = 0; i < 12; i++)
		{
			if(((Button)findViewById(R.id.month0 + i)).isSelected())
			{
				buffer.append(String.valueOf(i + 1));
				buffer.append(",");
			}
		}
		
		if(buffer.length() > 0)buffer.deleteCharAt(buffer.length() - 1);
		
		RequestParams params = new RequestParams();
		params.put("act", "myFootMark");
		params.put("userid", PreferencesUtils.getString(this, "userid"));
		params.put("year",((Button)findViewById(R.id.year)).getText().toString());
		params.put("month",buffer.toString());
		MgqRestClient.get(Constants.INFOMGT, params, loginHandler);
	}
	
	class MyAdapter extends BaseAdapter implements OnClickListener{
		public int getCount() {
			return mArray != null ? mArray.size() : 0;
		}

		public Object getItem(int position) {
			return null;
		}

		public long getItemId(int position) {
			return 0;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			FoodHolder foodHold = null;

			if (convertView == null) {
				LayoutInflater mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				foodHold = new FoodHolder();

				convertView = mInflater.inflate(R.layout.item_history, null);
				foodHold.city = (TextView) convertView.findViewById(R.id.city);
				foodHold.addr = (TextView) convertView.findViewById(R.id.addr);
				foodHold.sum = (TextView) convertView.findViewById(R.id.number);
				foodHold.top = (LinearLayout) convertView.findViewById(R.id.top);
				foodHold.line = (View) convertView.findViewById(R.id.line);
				foodHold.modify = (TextView) convertView.findViewById(R.id.modify);

				convertView.setTag(foodHold);
			} else {
				foodHold = (FoodHolder) convertView.getTag();
			}

			JSONObject item = mArray.getJSONObject(position);
			
			if(mStart.contains(Integer.valueOf(position))) foodHold.top.setVisibility(View.VISIBLE);
			else foodHold.top.setVisibility(View.GONE);

			if(mStart.contains(Integer.valueOf(position + 1))) foodHold.line.setVisibility(View.VISIBLE);
			else foodHold.line.setVisibility(View.GONE);

			foodHold.city.setText(item.getString("city"));
			if(item.getString("alias").length() > 0)
			{
				foodHold.addr.setText(item.getString("alias"));
			}
			else 
			{
				String place = item.getString("place");
				place = place.replaceFirst(item.getString("province"), "");
				place = place.replaceFirst(item.getString("city"), "");
				foodHold.addr.setText(place);
			}
	    
			foodHold.sum.setText(item.getString("number") + "个足迹");
			
			foodHold.modify.setTag(position);
			foodHold.modify.setOnClickListener(this);
			return convertView;
		}

		@Override
		public void onClick(View arg0) {
			mSelected = (Integer)arg0.getTag();
			findViewById(R.id.layout1).setVisibility(View.VISIBLE);
			
	    	if(mArray.getJSONObject(mSelected).getString("alias").length() > 0)
	    		((TextView)findViewById(R.id.content)).setText(mArray.getJSONObject(mSelected).getString("alias"));
	    	else ((TextView)findViewById(R.id.content)).setText(mArray.getJSONObject(mSelected).getString("place"));
		}
	}

	public final class FoodHolder {
		public TextView city;
		public TextView addr;
		public TextView sum;
		public View line;
		public TextView modify;
		public LinearLayout top;
	}

	public void reloadData() {
		mArray.removeAll(mArray);
		mAdapter.notifyDataSetChanged();
		sendHttpRequest();
	}
	
	private long mExitTime;
	 public boolean onKeyDown(int keyCode, KeyEvent event) 
	 {
		 if (keyCode == KeyEvent.KEYCODE_BACK) {
			 if ((System.currentTimeMillis() - mExitTime) > 2000) 
			 {
				 Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
				 mExitTime = System.currentTimeMillis();	
			 } else {
				 finish();
			 }
			 return true;
		 }
		 return super.onKeyDown(keyCode, event);
	 }
}
